import React, { useState, useRef, forwardRef, useImperativeHandle } from 'react';
import { Records, Select, Button } from '@block/plug';
import { Input, Tag, Modal, notification } from '@ss/mtd-react';
import M from '@block/utils';
import { LimitsAuthority } from '@src/utils';
import { TabStatus, PersonListStatus, RuleListData } from '../../type';
import { RuleDetailDrawer, RuleListDrawer } from '../index';
import URL from '../../url';

/** Public 方法 */
interface Handle {
  /** 获取搜索列表筛选条件 */
  getFilterValue: () => {
    [key: string]: any;
  };
  /** 筛选列表搜索刷新方法 */
  recordsSearch: () => void;
}

/** Props 声明 */
interface Props {
  /** 当前tab状态 */
  tabStatus: TabStatus;
  /** 更新tab角标数据方法 */
  getStatusCount: () => void;
  /** 当前页面权限数组 */
  pageActions: Array<LimitsAuthority>;
}

/**
 * 规则管理搜索列表
 */
const RuleManageRecords = forwardRef<Handle, Props>((props, ref) => {
  const { tabStatus, getStatusCount, pageActions } = props;

  /** state 声明 */
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]); // 表格的选中行
  const [detailDrawerVisible, setDetailDrawerVisible] = useState<boolean>(false); // 规则详情侧滑显示标志位
  const [ruleListDrawerVisible, setRuleListDrawerVisible] = useState<boolean>(false); // 规则名单侧滑显示标志位
  const [jobFamilyId, setJobFamilyId] = useState<string>(); // jobFamilyId参数保存

  /** ref 声明 */
  const RuleManageRecordsRef = useRef<Records>(null);

  /** this 变量 */
  const drawerModeThis = useRef<PageMode>('view'); // 详情侧滑drawer的状态
  const ruleIdThis = useRef<number>(); // 传给规则详情侧滑的id数据
  const batchDeleteThis = useRef<Array<number>>([]); // 批量删除的id数据

  /**
   * 规则列表查询数据
   * @param filter 筛选条件
   * @param page 分页信息
   * @returns 列表数据
   */
  const fetchData = async (filter, page: Page) => {
    filter.orgIdList = filter.orgIdList?.map((item) => item?.code);
    filter.sensitivePosTypeList = filter.sensitivePosTypeList?.map((item) => item?.code);
    filter.levelList = filter.levelList?.map((item) => item?.code);
    filter.jobGroupIdList = filter.jobGroupIdList?.map((item) => item?.code);
    filter.ruleStatus = filter.ruleStatus?.map((item) => item?.code);

    const params = { cond: { statusTab: tabStatus, ...filter }, page };
    const res = await M.$fetch<RuleListData>(URL.queryListByCondPage, params);
    return res;
  };

  /**
   * 点击查询按钮查询数据
   * @param e event
   * @param btn 按钮实例
   */
  const handleQuery = (e: MouseEvent, btn: Button) => {
    btn?.loading(true);
    RuleManageRecordsRef.current?.search().finally(() => {
      btn?.loading(false);
      // 清空之前的勾选数据
      setSelectedKeys([]);
    });
  };

  /**
   * 删除单行数据
   * @param ruleId 规则id
   */
  const handleDelete = (ruleId: number) => {
    Modal.warning({
      title: '提示',
      message: '确认删除吗？',
      closable: true,
      onOk: async () => {
        const res = await M.$fetch<OperateResponse>(URL.deleteRule, { ruleId });
        notification.success({ title: '成功', message: res?.message || '操作成功' });
        getStatusCount();
        RuleManageRecordsRef.current?.search().finally(() => {
          setSelectedKeys([]); // 清空之前的勾选数据
        });
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  /** 批量删除处理 */
  const handleBatchDelete = () => {
    Modal.warning({
      title: '提示',
      message: '确认批量删除吗？',
      closable: true,
      onOk: async () => {
        const res = await M.$fetch<OperateResponse>(URL.batchDeleteRule, { ruleIdList: batchDeleteThis.current });
        notification.success({ title: '成功', message: res?.message || '操作成功' });
        getStatusCount();
        RuleManageRecordsRef.current?.search().finally(() => {
          setSelectedKeys([]); // 清空之前的勾选数据
        });
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  /**
   * 获取Records的搜索条件数据
   * @returns 搜索列表的筛选条件
   */
  const getFilterValue = () => {
    const filterValue = RuleManageRecordsRef.current?.getFilterValue();
    // clone新变量，防止filter数据被改写，多次操作会有问题。
    const params = { ...filterValue };
    params.statusTab = tabStatus;
    params.levelList = params.levelList?.map((item) => item?.code);
    params.ruleStatus = params.ruleStatus?.map((item) => item?.code);
    params.orgIdList = params.orgIdList?.map((item) => item?.code);
    params.sensitivePosTypeList = params.sensitivePosTypeList?.map((item) => item?.code);
    params.jobGroupIdList = params.jobGroupIdList?.map((item) => item?.code);
    return params;
  };

  /** 搜索列表的刷新处理 */
  const recordsSearch = () => {
    RuleManageRecordsRef.current?.search();
  };

  useImperativeHandle(ref, () => ({
    getFilterValue,
    recordsSearch,
  }));

  // 控制不同tab下的搜索按钮布局
  let operateSpan = 8;
  switch (tabStatus) {
    case TabStatus.Audit:
    case TabStatus.All: {
      operateSpan = 16;
      break;
    }
    default: {
      operateSpan = 24;
    }
  }

  return (
    <div>
      <Records
        ref={RuleManageRecordsRef}
        labelInValue={false}
        onSearch={fetchData}
        onFilterValueChange={(key: string, value) => {
          if (key === 'jobFamilyId') {
            setJobFamilyId(value);
            RuleManageRecordsRef.current?.setFilterValue({ jobGroupIdList: null });
          }
        }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: [10, 20, 50, 100],
          defaultCurrent: 1,
          showTotal: true,
        }}
      >
        <Records.Form labelWidth="7em" labelInValue={false}>
          <Records.Form.Item formItemKey="orgIdList" label="适用组织：" span={8}>
            <Select
              keyField="code"
              labelField="name"
              multiple
              placeholder="请输入适用组织"
              dispatchFetchDataWithoutKeyword={false}
              toFormItem
              onFetchData={(search: string) =>
                M.$fetch<SelectOption<string>[]>(URL.queryOrgList, { search: search?.trim() })
              }
            />
          </Records.Form.Item>
          <Records.Form.Item formItemKey="levelList" label="职级：" span={8}>
            <Select
              keyField="code"
              labelField="name"
              multiple
              onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.queryLevelList)}
              placeholder="请选择职级"
              toFormItem
            />
          </Records.Form.Item>
          <Records.Form.Item formItemKey="jobFamilyId" label="JobFamily：" span={8}>
            <Select
              keyField="code"
              labelField="name"
              filterable={false}
              placeholder="请选择JobFamily"
              toFormItem
              onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.queryJobFamily)}
            />
          </Records.Form.Item>
          <Records.Form.Item formItemKey="jobGroupIdList" label="JobGroup：" span={8}>
            <Select
              keyField="code"
              labelField="name"
              disabled={!jobFamilyId}
              multiple
              filterable={false}
              placeholder="请选择JobGroup"
              toFormItem
              onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.queryJobGroupByJobFamilyId, { jobFamilyId })}
            />
          </Records.Form.Item>
          <Records.Form.Item formItemKey="sensitivePosTypeList" label="敏感岗位分类：" span={8}>
            <Select
              keyField="code"
              labelField="name"
              multiple
              filterable={false}
              onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.querySensitivePosTypeList)}
              placeholder="请选择敏感岗位分类"
              toFormItem
            />
          </Records.Form.Item>
          <Records.Form.Item formItemKey="ruleNumber" label="规则编号：" span={8}>
            <Input placeholder="请输入规则编号" toFormItem />
          </Records.Form.Item>
          {tabStatus === TabStatus.All && (
            <Records.Form.Item formItemKey="ruleStatus" label="状态：" span={8}>
              <Select
                keyField="code"
                labelField="name"
                multiple
                filterable={false}
                onFetchData={() => M.$fetch<SelectOption<number>[]>(URL.queryRuleStatusList)}
                placeholder="请选择状态"
                toFormItem
              />
            </Records.Form.Item>
          )}
          {tabStatus === TabStatus.Audit && (
            <Records.Form.Item formItemKey="bpmCode" label="审批单号：" span={8}>
              <Input placeholder="请输入审批单号" toFormItem maxLength={30} />
            </Records.Form.Item>
          )}
          <Records.Form.Item span={operateSpan}>
            <div style={{ textAlign: 'right' }}>
              <Button
                shape="text"
                type="primary"
                onClick={() => RuleManageRecordsRef.current?.resetFilterValueAndSearch()}
              >
                重置
              </Button>
              <Button style={{ minWidth: '80px', background: '#fff' }} ghost type="primary" onClick={handleQuery}>
                搜索
              </Button>
            </div>
          </Records.Form.Item>
        </Records.Form>
        <div>
          {[TabStatus.All, TabStatus.Valid].includes(tabStatus) && pageActions.includes(LimitsAuthority.batchDelete) && (
            <Button size="normal" type="primary" disabled={selectedKeys.length === 0} onClick={handleBatchDelete}>
              批量删除
            </Button>
          )}
        </div>
        <Records.Table
          useSticky
          scroll={{ x: true }}
          mode="row"
          rowSelection={
            [TabStatus.All, TabStatus.Valid].includes(tabStatus) && {
              fixed: 'left',
              selectedKeys,
            }
          }
          onSelectChange={(selectedKeyArray, selectedRows) => {
            batchDeleteThis.current = selectedRows.map((item) => item?.ruleId);
            setSelectedKeys(selectedKeyArray);
          }}
        >
          <Records.Table.Column dataKey="creatorEmpName" width="150">
            创建人
          </Records.Table.Column>
          <Records.Table.Column
            dataKey="createTime"
            width="160"
            render={(date: number) => (date ? M.datejs(date)?.format('YYYY-MM-DD HH:mm:ss') : '-')}
          >
            创建时间
          </Records.Table.Column>
          <Records.Table.Column dataKey="ruleNumber" width="100">
            规则编号
          </Records.Table.Column>
          <Records.Table.Column dataKey="version" width="60">
            版本
          </Records.Table.Column>
          <Records.Table.Column dataKey="orgNamePath" width="170" expand={{ mode: 'tooltip', minRows: 2 }}>
            适用组织
          </Records.Table.Column>
          <Records.Table.Column dataKey="jobFamilyName" width="100">
            JobFamily
          </Records.Table.Column>
          <Records.Table.Column dataKey="jobGropName" width="170" expand={{ mode: 'tooltip', minRows: 2 }}>
            JobGroup
          </Records.Table.Column>
          <Records.Table.Column dataKey="levelInfo" width="100">
            职级
          </Records.Table.Column>
          <Records.Table.Column dataKey="sensitivePosTypeNameList" width="170" expand={{ mode: 'tooltip', minRows: 2 }}>
            敏感岗位分类
          </Records.Table.Column>
          <Records.Table.Column
            dataKey="personListCount"
            width="60"
            render={(value, row) => {
              const { ruleId } = row;
              return (
                <Button
                  shape="text"
                  type="primary"
                  onClick={() => {
                    ruleIdThis.current = ruleId;
                    setRuleListDrawerVisible(true);
                  }}
                >
                  {value}
                </Button>
              );
            }}
          >
            名单
          </Records.Table.Column>
          <Records.Table.Column
            dataKey="ruleStatus"
            width="70"
            render={(value) => {
              let theme = null;
              let name = null;
              switch (value) {
                case PersonListStatus.needSubmit: {
                  name = '待提交';
                  theme = 'orange';
                  break;
                }
                case PersonListStatus.audit: {
                  name = '审批中';
                  theme = 'pure';
                  break;
                }
                case PersonListStatus.valid: {
                  name = '生效中';
                  theme = 'green';
                  break;
                }
                case PersonListStatus.invalid: {
                  name = '已失效';
                  theme = 'gray';
                  break;
                }
                case PersonListStatus.deleted: {
                  name = '已删除';
                  theme = 'red';
                  break;
                }
                default:
                  break;
              }
              return <Tag theme={theme}>{name}</Tag>;
            }}
          >
            状态
          </Records.Table.Column>
          <Records.Table.Column
            dataKey="actions"
            width="140"
            render={(value, row) => {
              return (
                <div>
                  {value.includes('view') && (
                    <Button
                      type="primary"
                      shape="text"
                      onClick={() => {
                        // 将当前行的数据id存起来给到drawer使用
                        ruleIdThis.current = row.ruleId;
                        drawerModeThis.current = 'view';
                        setDetailDrawerVisible(true);
                      }}
                    >
                      查看
                    </Button>
                  )}
                  {value.includes('modify') && (
                    <Button
                      type="primary"
                      shape="text"
                      onClick={() => {
                        // 将当前行的数据id存起来给到drawer使用
                        ruleIdThis.current = row.ruleId;
                        drawerModeThis.current = 'edit';
                        setDetailDrawerVisible(true);
                      }}
                    >
                      编辑
                    </Button>
                  )}
                  {value.includes('delete') && (
                    <Button type="primary" shape="text" onClick={() => handleDelete(row.ruleId)}>
                      删除
                    </Button>
                  )}
                </div>
              );
            }}
            fixed="right"
          >
            操作
          </Records.Table.Column>
        </Records.Table>
      </Records>
      {detailDrawerVisible && (
        <RuleDetailDrawer
          ruleId={ruleIdThis.current}
          drawerMode={drawerModeThis.current}
          setDetailDrawerVisible={setDetailDrawerVisible}
          getStatusCount={getStatusCount}
          recordsSearch={RuleManageRecordsRef.current?.search}
        />
      )}
      {ruleListDrawerVisible && (
        <RuleListDrawer ruleId={ruleIdThis.current} setRuleListDrawerVisible={setRuleListDrawerVisible} />
      )}
    </div>
  );
});

export default RuleManageRecords;
